package com.zhongge.dao.impl;

import com.zhongge.dao.UserDao;
import com.zhongge.entity.User;
import com.zhongge.util.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @ClassName UserDaoImpl
 * @Description TODO
 * @Author zhongge
 * @Version 1.0
 */
public class UserDaoImpl implements UserDao {

    /**
     * 根据用户对象获取用户信息
     * @param username 用户名
     * @return 用户对象
     */
    @Override
    public User getUserByUsername(String username) {
        //连接
        Connection conn = null;
        //数据库预操作对象
        PreparedStatement ps = null;
        //结果集
        ResultSet re = null;

        try {
            //获取连接
            conn = DBUtils.getConnection();

            //先写出含有张伟符号的sql语句（防止SQL注入）
            String sql = "select id, username, password from t_user where username = ?";

            //预编译sql语句 ==> 将sql传入到 预操作对象中 返回一个预编译sql的对象
            ps = conn.prepareStatement(sql);

            //对占位符进行填充
            ps.setString(1, username);

            //执行sql语句==》将sql传入到数据库中执行
            re = ps.executeQuery();

            //处理结果
            if (re.next()) {
                //创建User对象
                User user = new User();
                //对User中各个值进行初始化
                user.setId(re.getInt("id"));
                user.setUsername(re.getString("username"));
                user.setPassword(re.getString("password"));
                return user;
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtils.close(conn, ps, re);
        }
        return null;
    }

}
